package com.bifang.module.file.core.common.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.module.file.common.vo.FileLogVO;
import com.bifang.module.file.core.common.FileLogIntegration;
import com.bifang.module.file.dao.model.FileLog;
import com.bifang.module.file.dao.model.FileLogHistory;
import com.bifang.module.file.dao.service.FileLogHistoryService;
import com.bifang.module.file.dao.service.FileLogService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/** 通用文件服务日志保存 */
@Service
public class FileLogIntegrationImpl implements FileLogIntegration {
    @Autowired FileLogService fileLogService;
    @Autowired FileLogHistoryService fileLogHistoryService;

    @Override
    @Async("commonTaskExecutor")
    public void saveFileLog(FileLogVO fileLogVO) {
        if (fileLogVO.getFileId() == null) {
            fileLogVO.setFileId(BigDecimal.ZERO);
        }
        String msg = fileLogVO.getMessage();
        if (StringUtils.isNotBlank(msg)) {
            if (msg.length() >= 500) {
                fileLogVO.setMessage(msg.substring(0, 400));
            }
        }
        FileLog fileLog = Convert.convert(FileLog.class, fileLogVO);
        if (fileLog.getEndTime() == null) {
            fileLog.setEndTime(new Date());
        }
        if (fileLog.getYm() == null) {
            Integer ym =
                    Integer.parseInt(
                            DateUtil.format(DateUtil.date(), DatePattern.PURE_DATE_PATTERN)
                                    .substring(0, 6));
            fileLog.setYm(ym);
        }
        // 计算总耗时
        if (fileLog.getBegTime() != null && fileLog.getEndTime() != null) {
            BigDecimal takingTimeMs =
                    new BigDecimal(fileLog.getEndTime().getTime() - fileLog.getBegTime().getTime());
            BigDecimal takingTime =
                    takingTimeMs.divide(new BigDecimal(1000), 3, BigDecimal.ROUND_HALF_DOWN);
            fileLog.setTakingTime(takingTime);
        }
        fileLogService.save(fileLog);
        FileLogHistory fileLogHistory = Convert.convert(FileLogHistory.class, fileLog);
        fileLogHistoryService.save(fileLogHistory);
    }

    @Override
    public FileLogVO getByFileLogId(BigDecimal fileLogId) {
        FileLogHistory fileLog = fileLogHistoryService.getById(fileLogId);
        if (fileLog == null) {
            throw new AppException("找不到日志信息");
        }
        FileLogVO fileLogVO = Convert.convert(FileLogVO.class, fileLog);
        return fileLogVO;
    }
}
